import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import type { MealResult } from '@/types/goods'

// 定义 Store
export const useCartStore = defineStore(
  'cart',
  () => {

    const mealList = ref<MealResult[]>([])

    // 购物车信息
    const cartList = computed(() => {
      return mealList.value.filter((meal) => meal.count !== undefined && meal.count > 0)
    })

    const AllPrice = ref(0.00)

    const setAllPrice = (val : number) => {
      AllPrice.value = val;
    }
    // 计算选中总金额
    const selectedCartListMoney = computed(() => {
      return cartList.value.reduce((sum, item) => sum + item.count! * item.price, 0).toFixed(2)
    })

    // 计算选中带折扣的总金额
    const selectedCartListMoneyWithDiscount = computed(() =>
      cartList.value
        .filter((meal) => meal.discount !== undefined)
        .reduce((sum, item) => {
          if (!item.discount) {
            return sum + item.count! * item.price * 10! * 0.1
          } else {
            return sum + item.count! * item.price * item.discount! * 0.1
          }


        }, 0)
        .toFixed(2),
    )

    // 记得 return
    return {
      cartList,
      mealList,
      selectedCartListMoney,
      selectedCartListMoneyWithDiscount,
      AllPrice,
      setAllPrice
    }
  },
  {
    persist: true,
  },
)
